package com.shensi.appCollect.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.appCollect.pojo.CouponTemplate;
import com.shensi.appCollect.constantEnum.Constant;
import com.shensi.appCollect.controller.CouponController;
import com.shensi.appCollect.dao.CouponActivityIssueMapper;
import com.shensi.appCollect.dao.UserRecommendRecordMapper;
import com.shensi.appCollect.enums.DeliveryStatus;
import com.shensi.appCollect.enums.NewUserStatus;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.service.AppUserInfoService;
import com.shensi.appCollect.service.CouponActivityService;
import com.shensi.appCollect.service.EnterpriseService;
import com.shensi.appCollect.service.IUserRecommendRecordService;
import com.shensi.appCollect.utils.ResultData;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * @date 2024/1/17
 */
@Service
public class UserRecommendRecordServiceImpl extends ServiceImpl<UserRecommendRecordMapper, UserRecommendRecord> implements IUserRecommendRecordService {

    private static final Logger log = LoggerFactory.getLogger(UserRecommendRecordServiceImpl.class);

    @Autowired
    private CouponActivityService couponActivityService;
    @Autowired
    private CouponController couponController;
    @Autowired
    private CouponActivityIssueMapper couponActivityIssueMapper;
    @Autowired
    private AppUserInfoService appUserInfoService;
    @Autowired
    private EnterpriseService enterpriseService;

    @Override
    @Async
    public void updateRecordAndSendCoupons(Long recommendId, AppUserInfo newAppUser){
        if (newAppUser == null) {
            return;
        }
        UserRecommendRecord recommendRecord = getById(recommendId);
        if (recommendRecord == null) {
            return;
        }
        UserRecommendRecord update = new UserRecommendRecord();
        update.setId(recommendId);
        update.setNewUserStatus(NewUserStatus.ACTIVE);
        update.setNewUserId(Long.valueOf(newAppUser.getUserId()));
        update.setNewUserNickName(newAppUser.getBlogNickName());
        update.setNewMobilePhone(newAppUser.getMobilePhone());
        DeliveryStatus status = sendCoupon(recommendRecord);
        log.info("推荐有奖,发放结果:{}",status);
        update.setDeliveryStatus(status);
        updateById(update);
    }

    @Override
    @Async
    public void insertRecommendRecordAndSendCoupons(Integer sharedUserId,AppUserInfo newAppUser){
        if (newAppUser == null) {
            return;
        }
        AppUserInfo sharedUserInfo = appUserInfoService.getById(sharedUserId);
        if (sharedUserInfo == null) {
            return;
        }
        Enterprise enterprise = enterpriseService.selectEnterpriseInfo(sharedUserInfo.getStationId());
        UserRecommendRecord recommendRecord = new UserRecommendRecord();
        recommendRecord.setEnterpriseId(Long.valueOf(sharedUserInfo.getStationId()));
        recommendRecord.setEnterpriseName(enterprise == null ? null : enterprise.getEnterpriseName());
        recommendRecord.setOriginUserId(Long.valueOf(sharedUserInfo.getUserId()));
        recommendRecord.setOriginUserNickName(sharedUserInfo.getBlogNickName());
        recommendRecord.setOriginMobilePhone(sharedUserInfo.getMobilePhone());
        recommendRecord.setNewUserId(newAppUser.getUserId() == null ? null : Long.valueOf(newAppUser.getUserId()));
        recommendRecord.setNewUserNickName(newAppUser.getBlogNickName());
        recommendRecord.setNewMobilePhone(newAppUser.getMobilePhone());
        recommendRecord.setNewUserStatus(NewUserStatus.ACTIVE);
        recommendRecord.setDeliveryStatus(DeliveryStatus.NOT_SHIP);
        recommendRecord.setCreateTime(LocalDateTime.now());
        recommendRecord.setUpdateTime(LocalDateTime.now());
        save(recommendRecord);
        DeliveryStatus status = sendCoupon(recommendRecord);
        if (status != DeliveryStatus.NOT_SHIP) {
            UserRecommendRecord update = new UserRecommendRecord();
            update.setId(recommendRecord.getId());
            update.setDeliveryStatus(status);
            updateById(update);
        }
    }

    private DeliveryStatus sendCoupon(UserRecommendRecord recommendRecord){
        CouponActivity form = new CouponActivity();
        form.setEnterpriseId(recommendRecord.getEnterpriseId());
        form.setActivityStatus("1");
        form.setIssueType("6");
        form.setIsDeleted(Boolean.FALSE);
        List<CouponActivity> activities = couponActivityService.queryList(form);
        Date now = new Date();
        activities = activities.stream().filter(ca -> ca.getActivityStartTime().before(now) && ca.getActivityEndTime().after(now)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(activities)) {
            log.info("推荐有奖,优惠卷活动为空");
            return DeliveryStatus.NOT_SHIP;
        }
        List<String> activityIds = activities.stream().map(CouponActivity::getId).collect(Collectors.toList());
        log.info("推荐有奖,优惠卷活动id:{}",activityIds);
        LambdaQueryWrapper<CouponActivityIssue> qw = Wrappers.lambdaQuery(CouponActivityIssue.class);
        qw.in(CouponActivityIssue::getActivityId,activityIds);
        List<CouponActivityIssue> activityIssues = couponActivityIssueMapper.selectList(qw);
        if (CollectionUtils.isEmpty(activityIssues)) {
            log.info("推荐有奖,优惠卷为空");
            return DeliveryStatus.NOT_SHIP;
        }
        DrawCoupon drawCoupon = new DrawCoupon();
        drawCoupon.setMobilePhone(recommendRecord.getOriginMobilePhone());
        drawCoupon.setBizId(recommendRecord.getId());
        drawCoupon.setBizType(Constant.COUPON_USER_BIZ_TYPE_USER_RECOMMEND);
        drawCoupon.setRandomFlag(System.currentTimeMillis() + RandomStringUtils.randomNumeric(7));
        Map<String, List<String>> activityIdMap = activityIssues.stream().collect(Collectors.groupingBy(CouponActivityIssue::getActivityId, Collectors.mapping(CouponActivityIssue::getIssueId,Collectors.toList())));
        int allSize = activityIssues.size();
        log.info("推荐有奖,数量:{},优惠卷id:{}",allSize,activityIdMap);
        int drawCont = 0;
        Set<Map.Entry<String, List<String>>> entries = activityIdMap.entrySet();
        for (Map.Entry<String, List<String>> entry : entries) {
            String activityId = entry.getKey();
            List<String> issueIds = entry.getValue();
            if (CollectionUtils.isEmpty(issueIds)) {
                continue;
            }
            try {
                ResultData data = couponController.sendCoupon(drawCoupon, issueIds, 9, activityId, null, null);
                if (data.getRetCode() == 0 && data.getData() != null) {
                    List<CouponTemplate> data1 = (List<CouponTemplate>) data.getData();
                    log.info("推荐有奖,发放结果,activity:[{}],数量:[{}]",activityId,data1.size());
                    drawCont += data1.size();
                }
            } catch (Exception e) {
                log.error("发优惠劵失败", e);
            }
        }
        DeliveryStatus status;
        if (drawCont>0) {
            status = drawCont == allSize ? DeliveryStatus.SHIPPED : DeliveryStatus.PORTION_SHIP;
        }else{
            status = DeliveryStatus.SHIP_FAIL;
        }
        return status;
    }

}
